package com.hemh.job;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.hemh.entity.OmsBorrow;
import com.hemh.entity.OmsEmail;
import com.hemh.service.BookService;
import com.hemh.service.EmailService;
import com.hemh.service.UserService;
import com.hemh.utils.ExcuteLinuxCommandUtils;
import com.hemh.utils.SendMessageUtils;
import com.hemh.utils.ServerUtils;
import com.hemh.utils.TimeUtils;

/**
 * @author HeMingHui
 * @since 2020-10-18
 * @description 定时任务主类
 */
@Component
public class HemhJob {

	private static Logger logger = LoggerFactory.getLogger(HemhJob.class);
	
	@Value("${spring.mail.properties.from}")
	private String defaultEMailSender;

	@Resource
	private UserService userService;

	@Resource
	private BookService bookService;

	@Resource
	private EmailService emailService;

	@Resource
	private SendMessageUtils sendMessageUtils;

	// @Scheduled(cron = "0 0/2 * * * ?")
	@SuppressWarnings("unused")
	private void testJob() {
		logger.info("#####testJob执行了...");
		logger.info("----->Server IP = " + ServerUtils.getServerIP());
		logger.info("----->Server Name = " + ServerUtils.getServerName());
	}

	/** 清除Linux的缓存 */
	// @Scheduled(cron = "${cron.cleanLinuxCache}")
	@SuppressWarnings("unused")
	private void clearLinuxCacheJob() {
		LocalDateTime startTime = LocalDateTime.now(), endTime = LocalDateTime.now();
		startTime = TimeUtils.getLocalDateTimeNow();
		logger.info("--->清理开始时间 : " + startTime);
		try {
			String executeCmd = "echo 3 > proc/sys/vm/drop_caches";
			logger.info("--->执行命令 : " + executeCmd);
			ExcuteLinuxCommandUtils.exeCmd(executeCmd);
		} catch (Exception e) {
			e.printStackTrace();
		}
		endTime = TimeUtils.getLocalDateTimeNow();
		logger.info("--->清理结束时间 : " + endTime);
		logger.info("--->清理执行总时间 : " + TimeUtils.minusToMillsLocalDateTime(startTime, endTime) + "毫秒");
	}

	/**
	 * @author HeMingHui
	 * @since 2020-11-03
	 * @description 逾期未还书籍的提醒
	 */
	//@Scheduled(cron = "0 0/5 * * * ?") // 开发用
	// @Scheduled(cron = "${cron.unReturnBook}")
	private void scanUnReturnBookJob() {
		List<OmsBorrow> borrowList = new ArrayList<OmsBorrow>();
		borrowList = bookService.getBorrowListByIsReturn("0");
		borrowList.stream().forEach(item -> {
			/** 系统当前时间 */
			LocalDateTime nowTime = TimeUtils.getLocalDateTimeNow();
			/** 期望归还时间 */
			LocalDateTime exReturnTime = item.getExpectReturnTime();
			/** LocalDateTime转化为date */
			Date nowDate = TimeUtils.localDateTimeConvertToDate(nowTime);
			Date exReturnDate = TimeUtils.localDateTimeConvertToDate(exReturnTime);
			if (exReturnDate.before(nowDate)) {/** 超出期限, 当天到期 */
				String userNumber = item.getBookBorrower();
				int bookId = item.getBorrowBookId();
				/** 更新 Overdue相关字段 */
				bookService.updateBorrowOverdue(userNumber, bookId);
				String message = sendMessageUtils.sendReturnBookMessage(userNumber, bookId, nowTime, exReturnTime);
				String emailRecevier = userService.getUserInfoByUserNumber(userNumber).getEmail();
				/** 消息提醒插入邮件表 */
				emailService.insertEmailRecord(defaultEMailSender, emailRecevier, "消息提醒", message);
			}
		});
	}

	//@Scheduled(cron = "0 0/5 * * * ?") // 开发用
	// @Scheduled(cron = "${cron.sendEmail}")
	private void sendEmailJob() {
		/** 遍历邮件表, 找到未发送的邮件, 进行发送 */
		List<OmsEmail> emailList = new ArrayList<OmsEmail>();
		emailList = emailService.getEMailListByStatus("0");
		emailList.stream().forEach(item -> {
			/** 接通邮件服务器，进行异步发邮件 */
			new Thread(() -> {
				emailService.sendMimeMail(item);
			}).start();
			/** 更新邮件表记录状态 */
			item.setEmailStatus("1");
			item.setEmailSendTime(TimeUtils.getLocalDateTimeNow());
			emailService.updateEmailStatus(item);
		});
	}

}
